package com.qs.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;

import com.infomanage.dao.DeptDAO;
import com.infomanage.dao.PersonDAO;
import com.infomanage.po.Department;
import com.infomanage.po.Person;
import com.jiuqi.bi.chartpro.chart.linebox.LineBoxChart;
import com.jiuqi.bi.chartpro.chart.linebox.LineBoxChartModel;
import com.jiuqi.bi.chartpro.chart.linebox.LineSeries;
import com.jiuqi.bi.chartpro.chart.stack.StackChart;
import com.jiuqi.bi.chartpro.common.Alignment;
import com.jiuqi.bi.chartpro.common.BGColor;
import com.jiuqi.bi.chartpro.common.BgColorType;
import com.jiuqi.bi.chartpro.common.DataSymbol;
import com.jiuqi.bi.chartpro.common.GradientAlign;
import com.jiuqi.bi.chartpro.common.LineType;
import com.jiuqi.bi.chartpro.exception.ChartException;
import com.jiuqi.util.ColorUtil;
import com.jiuqi.webtree.util.StringUtils;
import com.qs.dao.QsAoTestDAO;
import com.qs.dao.QsCtMmoTestDAO;
import com.qs.dao.QsCtPhyTestDAO;
import com.qs.dao.QsGtTestDAO;
import com.qs.dao.QsTsTestDAO;
import com.qs.enums.ApparatusType;
import com.qs.enums.OperateType;
import com.qs.enums.TrainingSession;
import com.qs.vo.ColligateAnalResultItem;
import com.qs.vo.IndividualAnalResultItem;
import com.qs.vo.QsAoTestItem;
import com.qs.vo.QsCtMmoTestItem;
import com.qs.vo.QsCtPhyTestItem;
import com.qs.vo.QsGtTestItem;
import com.qs.vo.QsTsTestItem;

public class TestAnalyseService {

	public static byte[] analyseIndividual(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			String trainingSession = request.getParameter("trainingSession");// 训练项目
			String traineeIdStr = request.getParameter("traineeId");// 训练人
			if (StringUtils.isEmpty(traineeIdStr)
					|| StringUtils.isEmpty(trainingSession)) {
				return null;
			}
			String beginDate = request.getParameter("beginDate");// 起始时间
			String endDate = request.getParameter("endDate");// 截止时间
			String trainingSessionTitle = TrainingSession.valueOf(
					trainingSession).title();
			String[] traineeIds = traineeIdStr.split(";");
			List<IndividualAnalResultItem> items = new ArrayList<IndividualAnalResultItem>();
			int generalOperateTypeValue = 0;
			boolean isGeneralOperateType = false;
			int apparatusTypeValue = 0;
			boolean isApparatusType = false;
			switch (TrainingSession.valueOf(trainingSession)) {
			case GFZ:
				generalOperateTypeValue = OperateType.GFZ.value();
				isGeneralOperateType = true;
				break;
			case MBMF:
				generalOperateTypeValue = OperateType.MBMF.value();
				isGeneralOperateType = true;
				break;
			case ZMF:
				generalOperateTypeValue = OperateType.ZMF.value();
				isGeneralOperateType = true;
				break;
			case JMP:
				generalOperateTypeValue = OperateType.JMP.value();
				isGeneralOperateType = true;
				break;
			case TFJ:
				generalOperateTypeValue = OperateType.TFJ.value();
				isGeneralOperateType = true;
				break;
			case MHJ:
				generalOperateTypeValue = OperateType.MHJ.value();
				isGeneralOperateType = true;
				break;
			case DXQT:
				generalOperateTypeValue = OperateType.DXQT.value();
				isGeneralOperateType = true;
				break;
			case JSG:
				generalOperateTypeValue = OperateType.DXQT.value();
				isGeneralOperateType = true;
				break;
			case FOURH:
				apparatusTypeValue = ApparatusType.FOURH.value();
				isApparatusType = true;
				break;
			case O2:
				apparatusTypeValue = ApparatusType.O2.value();
				isApparatusType = true;
				break;
			case SUSHENGQI:
				apparatusTypeValue = ApparatusType.SUSHENGQI.value();
				isApparatusType = true;
				break;
			case WASI:
				apparatusTypeValue = ApparatusType.WASI.value();
				isApparatusType = true;
				break;
			case CO:
				apparatusTypeValue = ApparatusType.CO.value();
				isApparatusType = true;
				break;
			case OTHER:
				apparatusTypeValue = ApparatusType.OTHER.value();
				isApparatusType = true;
				break;
			case ZHENGYAO2:
				apparatusTypeValue = ApparatusType.ZHENGYAO2.value();
				isApparatusType = true;
				break;
			case ZHTZ:
				QsCtPhyTestDAO QsCtPhyTestDAO = new QsCtPhyTestDAO();
				List<IndividualAnalResultItem> list3 = QsCtPhyTestDAO.findByTraineeAndDate(
						traineeIds, beginDate, endDate);
				if (list3 != null) {
					items.addAll(list3);	
				}
				break;
			case WMPY:
				QsCtMmoTestDAO qsCtMmoTestDAO = new QsCtMmoTestDAO();
				List<IndividualAnalResultItem> list4 = qsCtMmoTestDAO.findByTraineeAndDate(
						traineeIds, beginDate, endDate);
				if (list4 != null) {
					items.addAll(list4);
				}
				break;
			case GWNBY:
				QsTsTestDAO qsTsTestDAO = new QsTsTestDAO();
				List<IndividualAnalResultItem> list5 = qsTsTestDAO.findByTraineeAndDate(
						traineeIds, beginDate, endDate);
				if (list5 != null) {
					items.addAll(list5);
				}
				break;
			}
			if(isGeneralOperateType) {
				QsGtTestDAO qsGtTestDAO = new QsGtTestDAO();
				List<IndividualAnalResultItem> list1 = qsGtTestDAO.findByTraineeAndDate(
						traineeIds, beginDate, endDate, generalOperateTypeValue);
				if (list1 != null) {
					items.addAll(list1);
				}
			}
			if(isApparatusType) {
				QsAoTestDAO qsAoTestDAO = new QsAoTestDAO();
				List<IndividualAnalResultItem> list2 = qsAoTestDAO.findByTraineeAndDate(
						traineeIds, beginDate, endDate, apparatusTypeValue);
				if (list2 != null) {
					items.addAll(list2);
				}
			}
			return buildIndividualChart(items, trainingSessionTitle);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static byte[] buildIndividualChart(
			List<IndividualAnalResultItem> items, String trainingSessionTitle) {
		StackChart chart = new StackChart();
		LineBoxChartModel lineBoxModel = chart.getChartModel();
		lineBoxModel.setTitle(trainingSessionTitle + "成绩趋势分析图");
		lineBoxModel.getLegend().setPosition(Alignment.Top);
		lineBoxModel.setHeight(380);
		lineBoxModel.setWidth(1050);
		lineBoxModel.getValueAxes()[0].setDecimal(3);
		lineBoxModel.setShowLegend(true);
		lineBoxModel.setShowTable(true);
		BGColor bgColor = new BGColor();
		bgColor.setGradAlign(GradientAlign.Horizontal);
		bgColor.setBgColorType(BgColorType.Custom);
		lineBoxModel.setBackground(bgColor);
		lineBoxModel.getValueAxes()[0].setTitle("分数");
		List<String> labels = new ArrayList<String>();
		HashMap<Integer, List<IndividualAnalResultItem>> finder = new HashMap<Integer, List<IndividualAnalResultItem>>();
		for (IndividualAnalResultItem individualAnalResultItem : items) {
			if (!labels.contains(individualAnalResultItem.getDate())) {
				labels.add(individualAnalResultItem.getDate());
			}
			if (finder.containsKey(individualAnalResultItem.getTraineeId())) {
				finder.get(individualAnalResultItem.getTraineeId()).add(
						individualAnalResultItem);
			} else {
				List<IndividualAnalResultItem> list = new ArrayList<IndividualAnalResultItem>();
				list.add(individualAnalResultItem);
				finder.put(individualAnalResultItem.getTraineeId(), list);
			}
		}
		int[] customColors = new int[] { 0x99ccff, 0xff7f3a, 0x1abebe, 0xaabbcc };
		int count = 0;
		for (Entry<Integer, List<IndividualAnalResultItem>> entry : finder
				.entrySet()) {
			List<IndividualAnalResultItem> itemList = entry.getValue();
			double[] data = new double[itemList.size()];
			for (int i = 0; i < itemList.size(); i++) {
				data[i] = itemList.get(i).getScore();
			}
			LineSeries series = new LineSeries(itemList.get(0).getTraineeName());
			series.setLineType(LineType.Curve);
			series.setDataSymbolSize(6);
			series.setWidth(3);
			series.setDataSymbolType(DataSymbol.CircleShape);
			series.setColor(customColors[count]);
			series.setShowValueLabel(true);
			series.setData(data);
			lineBoxModel.addSeries(series);
			count++;
		}
		// // 注册颜色
		// int[] customColors = new int[]{0x99ccff, 0xff7f3a, 0x1abebe,
		// 0xaabbcc};
		// chart.registerPalette("custom", customColors);
		// // 调整颜色板
		// chart.adjustPalette(ChartColorManager.PALETTE_B);
		lineBoxModel.getCategoryAxis().setLabels(
				labels.toArray(new String[labels.size()]));
		LineBoxChart lineBox = new LineBoxChart(lineBoxModel);
		try {
			byte[] imageBytes = lineBox.buildChart();
			return imageBytes;
		} catch (ChartException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 获取十六进制的颜色代码.例如 "#6E36B4" , For HTML ,
	 * 
	 * @return String
	 */
	public static int getRandColorCode() {
		String r, g, b;
		Random random = new Random();
		r = Integer.toHexString(random.nextInt(256)).toUpperCase();
		g = Integer.toHexString(random.nextInt(256)).toUpperCase();
		b = Integer.toHexString(random.nextInt(256)).toUpperCase();

		r = r.length() == 1 ? "0" + r : r;
		g = g.length() == 1 ? "0" + g : g;
		b = b.length() == 1 ? "0" + b : b;
		return ColorUtil.parseHexRGBColor(r + g + b);
	}

	public static byte[] analyseColligate(HttpServletRequest request,
			HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			String deptIdStr = request.getParameter("deptId");
			if (StringUtils.isEmpty(deptIdStr)) {
				return null;
			}
			String beginDate = request.getParameter("beginDate");// 起始时间
			String endDate = request.getParameter("endDate");// 截止时间
			QsGtTestDAO qsGtTestDAO = new QsGtTestDAO();
			List<ColligateAnalResultItem> items = qsGtTestDAO
					.findByDeptAndDate(Integer.parseInt(deptIdStr), beginDate,
							endDate);
			
			QsAoTestDAO qsAoTestDAO = new QsAoTestDAO();

			DeptDAO deptDAO = new DeptDAO();
			Department dept = deptDAO.findById(Integer.parseInt(deptIdStr));
			String deptName = "";
			if(dept != null) {
				deptName = dept.getPath();
			}
			return buildColligate(items, deptName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static byte[] buildColligate(
			List<ColligateAnalResultItem> items, String deptName) {
		StackChart chart = new StackChart();
		LineBoxChartModel lineBoxModel = chart.getChartModel();
		lineBoxModel.setTitle(deptName + "考核趋势分析图");
		lineBoxModel.getLegend().setPosition(Alignment.Top);
		lineBoxModel.setHeight(380);
		lineBoxModel.setWidth(1050);
		lineBoxModel.getValueAxes()[0].setDecimal(3);
		lineBoxModel.setShowLegend(true);
		lineBoxModel.setShowTable(true);
		BGColor bgColor = new BGColor();
		bgColor.setGradAlign(GradientAlign.Horizontal);
		bgColor.setBgColorType(BgColorType.Custom);
		lineBoxModel.setBackground(bgColor);
		lineBoxModel.getValueAxes()[0].setTitle("分数");
		List<String> labels = new ArrayList<String>();
		HashMap<Integer, List<ColligateAnalResultItem>> finder = new HashMap<Integer, List<ColligateAnalResultItem>>();
		for (ColligateAnalResultItem colligateAnalResultItem : items) {
			if (!labels.contains(colligateAnalResultItem.getDate())) {
				labels.add(colligateAnalResultItem.getDate());
			}
			if (finder.containsKey(colligateAnalResultItem.getTraineeId())) {
				finder.get(colligateAnalResultItem.getTraineeId()).add(
						colligateAnalResultItem);
			} else {
				List<ColligateAnalResultItem> list = new ArrayList<ColligateAnalResultItem>();
				list.add(colligateAnalResultItem);
				finder.put(colligateAnalResultItem.getTraineeId(), list);
			}
		}
		int[] customColors = new int[] { 0x99ccff, 0xff7f3a, 0x1abebe, 0xaabbcc };
		int count = 0;
		for (Entry<Integer, List<ColligateAnalResultItem>> entry : finder
				.entrySet()) {
			List<ColligateAnalResultItem> itemList = entry.getValue();
			double[] data = new double[itemList.size()];
			for (int i = 0; i < itemList.size(); i++) {
				data[i] = itemList.get(i).getScore();
			}
			LineSeries series = new LineSeries(itemList.get(0).getTraineeName());
			series.setLineType(LineType.Straight);
			series.setDataSymbolSize(6);
			series.setWidth(3);
			series.setDataSymbolType(DataSymbol.GlassSphereShape);
			series.setColor(customColors[count]);
			series.setShowValueLabel(true);
			series.setData(data);
			lineBoxModel.addSeries(series);
			count++;
		}
		// // 注册颜色
		// int[] customColors = new int[]{0x99ccff, 0xff7f3a, 0x1abebe,
		// 0xaabbcc};
		// chart.registerPalette("custom", customColors);
		// // 调整颜色板
		// chart.adjustPalette(ChartColorManager.PALETTE_B);
		lineBoxModel.getCategoryAxis().setLabels(
				labels.toArray(new String[labels.size()]));
		LineBoxChart lineBox = new LineBoxChart(lineBoxModel);
		try {
			byte[] imageBytes = lineBox.buildChart();
			return imageBytes;
		} catch (ChartException e) {
			e.printStackTrace();
		}

		return null;
	}
}
